<template>
  <view class="gather">
    <view class="page_content">
      <view class="shadow_box user_info" @click="goBack()">
        <image class="head_img" :src="userInfo.headimgurl" alt=""></image>
        <view class="user_name">{{userInfo.real_name}} ({{userInfo.mobile}})</view>
        <view class="right_arrow"><AtIcon  value='chevron-right' size='20' ></AtIcon></view>
      </view>
      <view class="shadow_box select_good" @click="show_equipment=true">
        <view class="good_left">
          <view class="good_topline">油品</view>
          <view class="good_bottomline">￥{{goodData.goods.price}}/升</view>
        </view>
        <view class="good_right">
          <view class="good_topline">{{goodData.name}} {{goodData.show_good}}</view>
          <view class="good_bottomline">共计：{{goodData.unit}}升</view>
        </view>
        <view class="right_arrow"><Icon name="arrow" size="20" class="arrow"/></view>
      </view>
      <view class="input_price" style="border: 1px solid rgba(63,172,254,1);">
        <view class="input_label">买单金额</view>
        <view class="input_value" @tap="show_keyboard=true">￥{{inputPrice}}</view>
      </view>
      <view class="input_price">
        <view class="input_label">会员优惠</view>
        <view class="discount_value">￥{{discountPrice}}</view>
      </view>
      <view class="input_price">
        <mutexComponent
          @openConponList="openConponList"
          @changeOption="changeOption"
          :sendStatus="true"
          :optionMutex="optionMutex"
          :vipdiscounts_status="vipdiscounts_status"
          :vipdiscounts="vipdiscounts"
          :conponOwnNum="conponOwnNum"
          :useNum="useNum"
          :bottom_ticket="bottom_ticket"
          :integralNum="integralNum"
          :dedIntegral="dedIntegral"
          :dedIntegralMoney="dedIntegralMoney"
          :mutexData="mutexData"
        ></mutexComponent>
        <view v-if="mutexData.length > 0">
          <view style="margin: 20px 0; color: red">
            以下优惠不同享
          </view>
          <mutexComponent
            @openConponList="openConponList"
            @changeOption="changeOption"
            :sendStatus="false"
            :optionMutex="optionMutex"
            :vipdiscounts_status="vipdiscounts_status"
            :vipdiscounts="vipdiscounts"
            :conponOwnNum="conponOwnNum"
            :useNum="useNum"
            :bottom_ticket="bottom_ticket"
            :integralNum="integralNum"
            :dedIntegral="dedIntegral"
            :dedIntegralMoney="dedIntegralMoney"
            :mutexData="mutexData"
          ></mutexComponent>
          <!-- 每升减，锁油价 -->
        </view>
        <el-button type="text" v-if="balanceAvailableStatus">
          该充值卡项共享受优惠{{ balanceAvailableMoney }}
        </el-button>
      </view>
      <view class="input_price">
        <view class="input_label">优惠券</view>
        <view class="discount_coupon" @click="show_coupon=true">
          <span v-if="selectCoupon">已减{{couponPrice}}元</span>
          <span v-else :class="{'colorGray':couponUsableNum==0}">{{couponUsableNum}} 张可用</span>
        </view>
      </view>
      <view class="remark">
        <AtInput
          name='value1'
          title='备注'
          type='text'
          placeholder='单行文本'
          value={this.state.value1}
        />
        <!-- <view class="remark_title">备注</view>
        <Field v-model="remark" input-align="right"></Field> -->
      </view>
      <view class="shadow_box">
        <view class="pay_title">选择支付方式</view>
        <view class="payment">
          <view class="payment_item" @tap="selectPay(index+ 1)" :class="{'pay_select':paySelect==index + 1}" v-for="(item,index) in payType" :key="index">
            <image :src="item.url" alt="" class="pay_icon"></image>
            <view class="pay_name">移动支付</view>
            <image src="../../assets/images/pay_select.png" v-if="paySelect== index + 1"  alt="" class="select_icon"></image>
          </view>
        </view>
      </view>
    </view>
    <view class="bottom_line">
      <view class="price">￥{{inputPrice}}</view>
      <view class="submit">立即支付</view>
    </view>
    <AtFloatLayout :isOpened="show_keyboard">
      <key-board @onCloseInput="closeInput" @onUpdateInput="updateInput"></key-board>
    </AtFloatLayout>
    <AtFloatLayout :isOpened="show_equipment" title="选择油枪" >
      <view class="equ_line">
        <view class="equ_item" v-for="(item,index) in equList" :key="item.id" @tap="selectEqu(index)">
          <view class="equ_name" v-if="item.show_num"><span>{{item.show_num}}</span>号油枪</view>
          <view class="equ_name" v-else></view>
          <view class="equ_good">{{item.show_good}}</view>
        </view>
      </view>
    </AtFloatLayout>
    <!-- <AtFloatLayout v-model="show_coupon" round  :style="{height:'400px'}">
      <tabs v-model="couponStatus" @change="getCouponList">
        <tab title="满减券" name="1"></tab>
        <tab title="代金券" name="3"></tab>
      </tabs>
      <view class="shadow_box coupon_ite" v-for="(item,index) in couponList" :key="index"></view>
    </AtFloatLayout> -->
  </view>
</template>

<script>
import Taro from '@tarojs/taro'
import "./getMoney.scss"
import KeyBoard from "../../components/myKeyboard"
import mutexComponent from "./mutexComponent.vue"
import Equipment from "../../api/equipment.js" // QrCode.EquipmentList 获取油枪列表
import Pay from "../../api/pay.js" 
import url1 from "../../assets/images/mobile_pay.png"
import url2 from "../../assets/images/cash_pay.png"
export default {
  data(){
    return{
      userInfo: {}, // 用户信息 路由传参
      goodData: {
        name: "选择油枪",
        unit: 0,
        show_good: "",
        goods_id: "",
        goods:{
          price: "",
        }
      }, // 选择的油枪，油品信息
      payType: [
        {
          title: "移动支付",
          url:url1,
        },
        {
          title: "移动支付",
          url:url1,
        },
        {
          title: "现金支付",
          url: url2,
        }
      ],
      inputPrice: "0", // 输入的消费金额
      discountPrice: "0", // 优惠金额
      show_keyboard: false, // 数字键盘弹窗
      remark: "", // 备注
      paySelect: "1", // 支付方式 1.移动支付 2.现金支付
      equList: [], // 油枪选项列表
      show_equipment: false, // 选择油枪弹窗
      equ_height: "300px", // 选择油枪弹窗高度
      cardDetail: {},
      firstIn: true, // 第一次进页面 选择油枪之后弹出金额键盘
      show_coupon: false, // 选择优惠券弹窗
      couponList: [], // 可用优惠券列表
      couponUsableNum: 0, // 可用优惠券数量
      selectCoupon: "", // 选择的优惠券
      selectCouponNum: 0, // 选择的优惠券数量
      couponPrice: 0, // 优惠券减的金额
      couponStatus: "1", // 优惠券类型 1.满减券 2.折扣券(作废) 3.代金券
      setpasswordPopStatus: false,
      dialogVisible: false,
      dialogVisiblePos: false,
      payPrice: 0, // 最终支付金额
      openMutex: false, // 积分互斥规则
      vipdiscounts: "", // 会员优惠
      conponList: [], // 优惠券列表
      conponType: "",
      useNum: 0, // 当前选中优惠券的数量
      bottom_ticket: `选择优惠券`, //优惠券提示
      couponIds: "", //优惠券id串
      upPrice: 0, // 上一次优惠券抵扣金额
      nowconponIdx: "", // 优惠券idx
      dedIntegral: 0, // 使用的抵扣积分
      dedIntegralMoney: 0, // 抵扣积分减免的钱
      conponOwnNum: 0,
      vipdiscounts_status: 1,
      activeName: "1",
      openIntegral: false, // 是否启用积分
      openMember: false, // 是否启用会员折扣
      num: "",
      couponradio: "",
      showDiscounts: false,
      remarkInput: "", // 备注
      drawer: false,
      payIndex: 0, // 支付方式选项
      pay_type: [],
      passwordPopStatus: false,
      forgetStatus: false,
      passwordForm: {
        confirmPassword: "",
        mobile: "",
        code: "",
        pay_pass: "",
        re_pay_pass: ""
      },
      code_num: "",
      code_text: "获取验证码",
      btn_status: false,
      timer: null,
      now_code: "",
      setStatus: false, //凑整设置
      mutexData: [], //后台设置项
      optionMutex: [], //互斥选项(前端选的)
      optionShell: ["1", "2", "3"], //页面所有选项值(1 积分 2 优惠券  3 会员折扣)
      choseVipDiscount: "", //用于计算优惠的会员折扣（）
      isInvoice: false,
      BalancePaySet: {
        user_level: 1,
        coupon_status: 1,
        points_status: 1
      }, //余额优惠项
      balanceAvailableStatus: false,
      balanceAvailableMoney: ""
    }
  },
  components: {
    KeyBoard,
    mutexComponent
  },
  mounted(){
    try {
      this.userInfo = JSON.parse(Taro.getStorageSync('userInfo'))
        console.log("userInfo",this.userInfo);
      if (this.userInfo) {
        this.init();
      }
    } catch (e) {
      // Do something when catch error
    }
    // this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
    // console.log("userInfo",this.userInfo);
    // this.init();
    // this.details(); //互斥获取
    // this.configuration();
    // // 会员卡
    // this.goPayMoney();
    // this.getBalancePaySet();
  },
  methods:{
    closeInput(){  // 关闭数字键盘弹窗
      this.show_keyboard = false
    },
    updateInput(val){  // 更新输入的金额
      this.inputPrice = val;
      console.log("数字", this.inputPrice);
      this.computeUnit();
    },
    selectPay(i){  // 选择支付方式
      this.paySelect = i;
    },
    goBack(){  // 返回上一个/重新选择客户
      // this.$router.go(-1)
      Taro.navigateTo({
        url: "/pages/getMoney/selectClient"
      })
    },
    init(){  // 初始化 获取油枪列表
      this.getEquList();
    },
    async getEquList(){
      var data = {
        page: 1,
        limit: 20,
      }
      const res = await Equipment.equipmentList(data);
      if (res.code == 200) {
        this.equList = res.data;
        this.equList.forEach(item => {
          item.show_good = item.goods.name + item.goods.type.name;
          item.show_num = parseInt(item.name);
          item.selected = false;
        })
        console.log('equList:',this.equList)
        if(this.equList.length > 9){
          this.equ_height = "380px"
        }
        this.show_equipment = true;
      } else{
        console.log(res);
        // Toast.fail('网络错误...')
      }
      // Toast.clear();
    },
    selectEqu(i){ // 选择油枪
      this.goodData = Object.assign({},this.equList[i]);
      this.show_equipment = false;
      this.computeUnit();
      if(this.firstIn){
        this.show_keyboard = true;
        this.firstIn = false;
      }
    },
    computeUnit(){ // 计算升数
      if(this.goodData.goods.price != ""){
        this.goodData.unit = (Number(this.inputPrice) / Number(this.goodData.goods.price)).toFixed(2);
        if(this.inputPrice){ // 获取可用优惠券
          this.getCouponList();
        }
      }
    },
    async getCouponList(){ // 获取可用优惠券
      var data = {
        goods_id: this.goodData.goods_id,
        money: this.inputPrice,
        status: this.couponStatus
      }
      const res = await Pay.getUsableCoupon(data)
      if(res.code == 200){
        this.couponList = res.data;
        this.couponUsableNum = res.num;
      }
    },
    // 余额支付设置
    getBalancePaySet() {
      // this.page++;
      let data = {
        token: this.token,
        app_id: this.app_id
      };
      balanceData(data).then(res => {
        console.log("unionData222: ", res);
        if (res.code == 200) {
          this.BalancePaySet = JSON.parse(res.data.type);
        }
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
          document.getElementById("qrcode").innerHTML = "";
          setTimeout(() => {
            location.reload();
          }, 100);
        })
        .catch(_ => {});
    },
    handleClosePos(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
          setTimeout(() => {
            location.reload();
          }, 500);
        })
        .catch(_ => {});
    },
    // 不使用优惠
    noCounpon() {
      this.drawer = false;
      this.couponradio = "";
      this.noUseconpon();
      // 重新計算金額
      this.calculatePrice();
      //
    },
    changeOption(val) {
      let oldData = val;
      this.optionMutex = [];
      let metexShell = []; //互斥的选项
      oldData.forEach(item => {
        if (!this.mutexData.includes(item)) {
          this.optionMutex.push(item);
        } else {
          metexShell.push(item);
        }
      });
      if (metexShell.length) {
        // this.$message.warning("优惠互斥，优惠不同享！！");
        this.optionMutex.push(metexShell[metexShell.length - 1]);
      }

      // this.optionMutex.forEach(item => {
      //   if (item == "1") {
      //     this.get_point();
      //   } else if (item == "2") {
      //     this.getAvailable_coupon();
      //     this.setDefault();
      //   } else if (item == "3") {
      //     this.choseVipDiscount = this.vipdiscounts;
      //   }
      // });
      // this.calculatePrice();
      this.minimumAnew();
      // } else {
      //   this.dedIntegral = 0;
      //   this.dedIntegralMoney = 0;
      //   this.calculatePrice();
      // }
    },
    // 优惠项数据重新加载
    minimumAnew() {
      console.log("什么时候调用 minimumAnew");
      // 重新計算价格
      // 1.积分清空
      this.dedIntegral = 0;
      this.dedIntegralMoney = 0;
      // 2.优惠券清空
      this.couponradio = "";
      this.noUseconpon();
      // 3.会员折扣清空
      this.choseVipDiscount = "";
      this.optionMutex.forEach(item => {
        if (item == "1") {
          this.get_point();
        } else if (item == "2") {
          this.getAvailable_coupon();
          this.setDefault();
        } else if (item == "3") {
          this.choseVipDiscount = this.vipdiscounts;
        }
      });
      this.calculatePrice();
    },
    chosePayType(index) {
      this.payIndex = index;
      //
      let code = this.pay_type[index].payment_code;
      console.log(
        "新增余额支付情!!",
        code,
        this.BalancePaySet,
        this.optionMutex
      );
      if (
        code == "balance" ||
        code == "family_balance" ||
        code == "team_balance" ||
        code == "card_balance"
      ) {
        let Available = {
          token: this.token,
          app_id: this.app_id,
          uid: this.user_infor[0].uid,
          payment_code: code,
          account_id: this.pay_type[this.payIndex].id,
          goods_id: this.oil_infor ? this.oil_infor.goods_id : 0,
          money: this.$parent.inputPrice,
          room_id: 0
        };
        accountAvailable(Available).then(res => {
          if (res.code == 200) {
            this.balanceAvailableStatus = true;
            this.balanceAvailableMoney = res.total_discount;
          } else {
            this.balanceAvailableStatus = false;
            this.balanceAvailableMoney = "";
          }
          console.log("我请求玩  价格", this.balanceAvailableMoney);
          // 新增余额支付情况 1 积分 2 优惠券  3 会员折扣
          if (this.BalancePaySet.user_level == 1) {
            let indexs = this.optionMutex.findIndex(item => {
              return item == 3;
            });
            console.log("新增余额支付情!!", indexs);
            if (indexs !== -1) {
              this.optionMutex.splice(indexs, 1);
            }
          }
          if (this.BalancePaySet.coupon_status == 1) {
            let indexs = this.optionMutex.findIndex(item => {
              return item == 2;
            });
            console.log("新增余额支付情!!", indexs);
            if (indexs !== -1) {
              this.optionMutex.splice(indexs, 1);
            }
          }
          if (this.BalancePaySet.points_status == 1) {
            let indexs = this.optionMutex.findIndex(item => {
              return item == 1;
            });
            console.log("新增余额支付情!!", indexs);
            if (indexs !== -1) {
              this.optionMutex.splice(indexs, 1);
            }
          }
          this.minimumAnew();
        });
      } else {
        this.optionMutex = this.pitchSet();
        this.changeOption(this.optionMutex);
      }
      // let status = await this.configuration();
      // if (index == 0 && this.setStatus) {
      //   this.payPrice = Number(this.payPrice).toFixed(0);
      // }
    },
    configuration() {
      var data = {
        token: this.token,
        app_id: this.app_id
      };
      getConfigButton(data).then(res => {
        if (res.code == 200) {
          console.log(res.data);
          res.data.value.forEach(item => {
            if (item.name == "cash_int") {
              this.setStatus = item.status == 1 ? true : false;
              console.log("凑整配置 状态", this.setStatus);
            } else if (item.name == "receipt_button") {
              this.isInvoice = item.status == 1 ? true : false;
            }
          });
        }
      });
      // getCouponSetting(data).then(res => {
      //   console.log("请求数据", res);
      //   // if (res.data.offline_buy != "") {
      //   //   this.offline_buy = res.data.offline_buy.split(",");
      //   // }
      // });
    },
    handlePassworld() {
      this.$confirm("确认关闭？")
        .then(_ => {
          this.passwordForm = {
            confirmPassword: "",
            mobile: "",
            code: "",
            pay_pass: "",
            re_pay_pass: ""
          };
          this.setpasswordPopStatus = false;
          this.passwordPopStatus = false;
        })
        .catch(_ => {});
    },
    //重置密码
    resetPassworld(type) {
      // type 1 重置 2 设置
      let data = {
        app_id: this.app_id,
        token: this.token,
        mobile: this.passwordForm.mobile,
        code: this.passwordForm.code,
        pay_pass: this.passwordForm.pay_pass,
        re_pay_pass: this.passwordForm.re_pay_pass
      };
      setPayPass(data).then(res => {
        console.log("122", res);
        if (res.code == 200) {
          this.$message.success("成功！！");
          this.passwordForm = {
            confirmPassword: "",
            mobile: "",
            code: "",
            pay_pass: "",
            re_pay_pass: ""
          };
          if (type == 1) {
            this.forgetStatus = false;
          } else {
            // 设置完密码
            this.setpasswordPopStatus = false;
            this.passwordPopStatus = true;
            this.forgetStatus = false;
          }
        } else {
          this.$message.warning(res.msg);
        }
      });
    },
    // 密码弹窗
    passwordldPop() {
      let payment = this.pay_type[this.payIndex].payment_code;
      console.log("payment", payment);
      if (
        payment != "cash" &&
        payment != "unionpay" &&
        payment != "wxpay" &&
        payment != "pos"
      ) {
        let data = {
          app_id: this.app_id,
          uid: this.user_infor[0].uid
        };
        judgePayPass(data).then(res => {
          console.log("验证", res);
          this.passwordForm.mobile = this.user_infor[0].mobile;
          if (res.code == 200) {
            this.passwordPopStatus = true;
          } else {
            // 没有密码
            this.setpasswordPopStatus = true;
          }
        });
      } else {
        this.settleAccounts();
      }
    },
    changeIc() {
      console.log("ka", this.passwordForm.confirmPassword.length);
      if (this.passwordForm.confirmPassword.length == 6) {
        console.log("ka");
        let data = {
          token: this.token,
          app_id: this.app_id,
          uid: this.user_infor[0].uid,
          pay_pass: this.passwordForm.confirmPassword
        };
        verifyPayPass(data).then(res => {
          if (res.code == 200) {
            this.$message.success("密码正确！！");
            this.settleAccounts();
            this.passwordPopStatus = false;
          } else {
            this.$message.warning(res.msg);
          }
          console.log("数据", res);
        });
      }
    },
    getCode(type = 0) {
      console.log("type", type);
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        if (type == 0) {
          this.SendMyCode();
        } else {
          this.SendUserCode();
        }
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
            this.code_text = this.count + "s";
            this.btn_status = true;
          } else {
            this.btn_status = false;
            this.timer = null;
            this.code_text = "获取验证码";
          }
        }, 1000);
      }
    },
    // 向用户发送验证码
    async SendUserCode() {
      try {
        var data = {
          app_id: this.app_id,
          token: this.token,
          mobile: this.passwordForm.mobile
        };
        const res = await iCSendSms(data);
        if (res.code == 200) {
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 计算金额
    calculatePrice() {
      //
      // 计算加油量
      this.$parent.fuel_charge = Number(
        (this.$parent.inputPrice / this.$parent.oil_infor.goods.price).toFixed(
          2
        )
      );
      //凑整
      let newNumber = 2;
      if (this.setStatus) {
        newNumber = this.payIndex == 0 ? 0 : 2;
      }
      // 计算会员折扣的金额
      // this.optionMutex

      if (this.vipdiscounts_status == 0) {
        //计算最后支付价格 金额-积分-优惠券
        this.payPrice = (
          this.$parent.inputPrice -
          this.dedIntegralMoney -
          this.upPrice
        ).toFixed(newNumber);
      } else if (this.vipdiscounts_status == 1) {
        //计算最后支付价格 （金额-积分-优惠券）* 折扣
        let numbers =
          this.choseVipDiscount == ""
            ? this.$parent.inputPrice - this.dedIntegralMoney - this.upPrice
            : ((this.$parent.inputPrice -
                this.dedIntegralMoney -
                this.upPrice) *
                this.choseVipDiscount) /
              10; // this.payPrice = ( //   ((this.$parent.inputPrice - this.dedIntegralMoney - this.upPrice) * //     this.choseVipDiscount) / //   10 // ).toFixed(newNumber);
        this.payPrice = numbers.toFixed(newNumber);
      } else if (this.vipdiscounts_status == 2) {
        //计算最后支付价格 （金额-积分-优惠券-每升减）
        let vip_youhui_price =
          Math.round(this.$parent.fuel_charge * this.choseVipDiscount * 100) /
          100;
        console.log("计算最后支付价格会员折扣", vip_youhui_price);
        this.payPrice = (
          this.$parent.inputPrice -
          vip_youhui_price -
          this.dedIntegralMoney -
          this.upPrice
        ).toFixed(newNumber);
      } else {
        //计算最后支付价格 （金额-积分-优惠券-直接减或者每升减优惠直接减）
        this.payPrice = (
          this.$parent.inputPrice -
          this.choseVipDiscount -
          this.dedIntegralMoney -
          this.upPrice
        ).toFixed(newNumber);
      }
      // 新增每升减，锁油价
      let a = this.payPrice;
      if (this.balanceAvailableStatus) {
        this.payPrice = a - Number(this.balanceAvailableMoney);
      }

      console.log("数据每升减价格", this.payPrice, this.balanceAvailableMoney);
      if (this.payPrice < 0) {
        this.payPrice = 0;
      }
    },
    // 获取vip优惠
    // getVipDiscount(id, cate, goods_id, money) {
    //   let vipData = {
    //     token: this.token,
    //     app_id: this.app_id,
    //     id,
    //     cate,
    //     goods_id,
    //     money
    //   };
    //   getVipDiscount(vipData).then(res => {
    //     if (res.code == 200) {
    //       console.log("会员折扣", res);
    //       this.vipdiscounts_status = res.data.status;
    //       if (res.data.status == 1) {
    //         this.vipdiscounts = res.data.zhe / 10;
    //       } else if (res.data.status == 2) {
    //         this.vipdiscounts = res.data.money;
    //       } else {
    //         this.vipdiscounts = "暂无优惠信息";
    //       }
    //       this.optionMutex = this.pitchSet();
    //       this.changeOption(this.optionMutex);
    //     }
    //   });
    // },
    // 结账
    settleAccounts() {
      // this.$refs.pay_Success.paySuccess = true;
      console.log(1212);
      let data = {
        app_id: this.app_id,
        token: this.token,
        cate_id: this.oil_infor.id,
        money: this.inputPrice,
        message: this.remarkInput,
        payment_code: this.pay_type[this.payIndex].payment_code, //
        point: this.dedIntegral,
        coupon_id: this.couponIds,
        coupon_type: 1,
        // memberStatus:
        num: this.useNum,
        uid: this.user_infor[0].uid,
        room_id: this.$parent.room_id,
        recharge: 0,
        memberStatus: this.choseVipDiscount != "" ? 1 : 0, //会员是否有优惠
        operator_id: localStorage.getItem("choseStaffId")
          ? localStorage.getItem("choseStaffId")
          : "" //员工ID
      };
      let typePayCode = this.pay_type[this.payIndex].payment_code;
      if (
        typePayCode != "cash" &&
        typePayCode != "unionpay" &&
        typePayCode != "wxpay" &&
        typePayCode != "pos"
      ) {
        data.account_id = this.pay_type[this.payIndex].id;
        data.pay_password = this.passwordForm.confirmPassword;
      }
      cashCreateOrder(data).then(res => {
        console.log("数据", res);
        if (res.code == 200) {
          if (
            res.payment_code == "cash" ||
            res.payment_code == "card_balance" ||
            res.payment_code == "balance" ||
            res.payment_code == "family_balance" ||
            res.payment_code == "team_balance"
          ) {
            let orderData = {
              app_id: this.app_id,
              token: this.token,
              ordersn: res.data.ordersn
            };
            oilsOrder(orderData).then(res => {
              this.$refs.pay_Success.orderData = res.data[0];
              this.$refs.pay_Success.paySuccess = true;
              this.$parent.inputPrice = "";
            });
          } else if (
            res.payment_code == "unionpay" ||
            res.payment_code == "wxpay" ||
            res.payment_code == "pos"
          ) {
            if (typeof res.data == "string") {
              this.dialogVisible = true;
              this.$nextTick(() => {
                let qrcode = new QRCode("qrcode", {
                  width: 360,
                  height: 360, // 高度
                  text: res.data // 二维码内容
                });
              });
            } else {
              this.dialogVisiblePos = true;
            }
            let result = setInterval(() => {
              searchOrder({ token: this.token, ordersn: res.ordersn }).then(
                res => {
                  if (res.code == 200) {
                    clearInterval(result);
                    if (this.payIndex == 3) {
                      this.dialogVisiblePos = false;
                    } else {
                      this.dialogVisible = false;
                    }
                    this.$alert(
                      `${this.pay_type[this.payIndex].name}支付成功, 请用户查看${this.pay_type[this.payIndex].name}消息通知`,
                      "充值成功",
                      {
                        confirmButtonText: "确定",
                        callback: action => {
                          this.timer = null;
                          location.reload();
                        }
                      }
                    );
                  }
                }
              );
            }, 4000);
          }
        } else {
          this.$message(res.msg);
        }
        this.passwordForm = {
          confirmPassword: "",
          mobile: "",
          code: "",
          pay_pass: "",
          re_pay_pass: ""
        };
      });
    },
    // 展示支付方式
    goPayMoney() {
      var obj = {
        type_id: this.oil_infor ? this.oil_infor.goods.type_id : 0,
        goods_id: this.oil_infor ? this.oil_infor.goods_id : 0,
        room_id: this.$parent.room_id,
        amount: this.inputPrice,
        uid: this.user_infor ? this.user_infor[0].uid : ""
      };
      this.getAllType(obj);
    },
    // 筛选油卡、车队卡、亲属卡支付方式
    async getCardPayType(obj, url) {
      try {
        const { type_id, goods_id, room_id, amount, uid } = obj;
        var res = await CardAvailable(url, {
          app_id: this.app_id,
          token: this.token,
          type_id,
          goods_id,
          room_id,
          amount,
          uid
        });
        return res.data.length ? res.data : [];
      } catch (error) {
        console.log(error);
      }
    },
    // 整合获取会员卡优惠，优惠券优惠
    discountAll(id, cate, goods_id, money) {
      console.log("获取全部类型优惠0");
      let data = {
        token: this.token,
        app_id: this.app_id,
        money: this.$parent.inputPrice,
        uid: this.user_infor ? this.user_infor[0].uid : "",
        status: this.activeName,
        goods_id: this.$parent.oil_infor.goods.id
      };
      let vipData = {
        token: this.token,
        app_id: this.app_id,
        id,
        cate,
        goods_id,
        money
      };
      let couponArr = getAvailable_coupon(data);
      let vipArr = getVipDiscount(vipData);

      return Promise.all([couponArr, vipArr]).then(res => {
        if (res[0].code == 200) {
          if (res[0].data.length > 0) {
            for (let i = 0; i < res[0].data.length; i++) {
              const element = res[0].data[i];
              if (element.id == this.couponradio) {
                element.stepperVal = this.useNum;
              } else {
                element.stepperVal = 1;
              }
              this.conponList.push(element);
              console.log("coupon list", this.conponList);
            }
            this.conponOwnNum = res[0].num;
          }
        } else {
          this.upPrice = 0;
          this.calculatePrice();
        }
        if (res[1].code == 200) {
          console.log("vipwozou");
          this.vipdiscounts_status = res[1].data.status;
          if (res[1].data.status == 1) {
            this.vipdiscounts = res[1].data.zhe / 10;
          } else if (res[1].data.status == 2) {
            this.vipdiscounts = res[1].data.money;
          } else if (res[1].data.status == 3 || res[1].data.status == 4) {
            this.vipdiscounts = res[1].data.every.discount;
          } else {
            this.vipdiscounts = "暂无优惠信息";
          }
        }
        this.optionMutex = this.pitchSet();
        this.changeOption(this.optionMutex);
      });
    },
    // 显示优惠券列表
    openConponList() {
      console.log("chufa显示优惠券列表");
      //选择优惠券
      if (!this.optionMutex.includes("2")) {
        return this.$message.warning("您还没有勾选是否进行优惠券使用！！");
      }
      console.log("chufa显示优惠券列表", this.conponList);
      if (this.conponList.length == 0) {
        this.getAvailable_coupon(true);
      }
      this.drawer = true;
    },
    // 获取优惠券列表
    getAvailable_coupon(present = false) {
      this.noUseconpon(present);
      let data = {
        token: this.token,
        app_id: this.app_id,
        money: this.$parent.inputPrice,
        uid: this.user_infor[0].uid,
        status: this.activeName,
        goods_id: this.$parent.oil_infor.goods.id
      };
      getAvailable_coupon(data).then(res => {
        if (res.code == 200) {
          console.log("获取全部类型优惠2");

          if (res.data.length > 0) {
            for (let i = 0; i < res.data.length; i++) {
              const element = res.data[i];
              if (element.id == this.couponradio) {
                element.stepperVal = this.useNum;
              } else {
                element.stepperVal = 1;
              }
              this.conponList.push(element);
            }
            this.conponOwnNum = res.num;
            // if (!present) {
            //   this.setDefault();
            // }
            if (this.optionMutex.includes("2")) {
              this.setDefault();
            }
          }
        }
        // } else {
        //   this.upPrice = 0;
        //   this.calculatePrice();
        // }
      });
    },
    //设置默认优惠券
    judgeUse(predict, use_num, use_limit) {
      let ultimatelyNum = "";
      if (predict > use_num && use_num > use_limit) {
        // 预计大于拥有且拥有大于最大使用
        ultimatelyNum = use_limit;
      } else if (predict > use_num && use_num < use_limit) {
        // 预计大于拥有且拥有小于最大使用
        ultimatelyNum = use_num;
      } else if (predict > use_num && use_num == use_limit) {
        // 预计大于拥有且拥有==最大使用
        ultimatelyNum = use_num;
      } else if (predict < use_num && predict > use_limit) {
        // 预计小于拥有且预计大于最大使用
        ultimatelyNum = use_limit;
      } else if (predict < use_num && predict < use_limit) {
        // 预计<拥有且预计<最大使用
        ultimatelyNum = predict;
      } else if (predict < use_num && predict == use_limit) {
        // 预计<拥有且预计==最大使用
        ultimatelyNum = predict;
      } else if (predict == use_num && predict > use_limit) {
        // 预计= 拥有且预计<最大使用
        ultimatelyNum = use_limit;
      } else if (predict == use_num && predict < use_limit) {
        // 预计=拥有且预计<最大使用
        ultimatelyNum = predict;
      } else {
        // 预计=拥有且预计=最大使用
        ultimatelyNum = predict;
      }
      // if (type == 1) {
      //   this.useNum = ultimatelyNum
      // } else {
      return ultimatelyNum;
      // }
    },
    setDefault() {
      let moneydata = [];
      let numData = [];
      let predict_uses = ""; // 有门槛预计
      let no_predict_uses = ""; // 无门槛预计
      let pitch_on = ""; // 使用数量

      for (let i = 0; i < this.conponList.length; i++) {
        const element = this.conponList[i];
        if (element.coupon_data.m_enough_money > 0) {
          //判断可使用数量 有门槛
          predict_uses = parseInt(
            this.$parent.inputPrice / element.coupon_data.m_enough_money
          ); // 预估使用
          pitch_on = this.judgeUse(
            predict_uses,
            element.use_num,
            element.coupon_data.use_limit
          );
        } else {
          //无门槛
          no_predict_uses = parseInt(
            this.$parent.inputPrice / element.coupon_data.m_dec_money
          ); // 预估使用
          pitch_on = this.judgeUse(
            no_predict_uses,
            element.use_num,
            element.coupon_data.use_limit
          );
        }
        numData.push(pitch_on);
        moneydata.push(element.coupon_data.m_dec_money * pitch_on);
      }
      for (let x = 0; x < moneydata.length; x++) {
        const element = moneydata[x];
        if (element == Math.max(...moneydata)) {
          this.useNum = numData[x];
          this.conponList[x].stepperVal = this.useNum;
          if (
            Number(this.conponList[x].coupon_data.m_dec_money) >
            Number(this.$parent.inputPrice)
          ) {
            this.calculatePrice();
            return; // 判断是否用券
          }
          this.set_radio(this.conponList[x]);
          break;
        }
      }
    },
    changeYhjNum(newVal, oldval) {
      setTimeout(() => {
        if (newVal > oldval) {
          this.useMulti(this.conponList[this.nowconponIdx], this.nowconponIdx);
        } else {
          this.useReduce(this.conponList[this.nowconponIdx]);
        }
      }, 200);
    },
    useMulti(item, idx) {
      if (item.coupon_data.m_enough_money > 0) {
        // 右门槛
        if (
          item.coupon_data.m_enough_money * item.stepperVal >
            this.$parent.inputPrice ||
          item.coupon_data.d_face_value * item.stepperVal >
            this.$parent.inputPrice
        ) {
          this.$message(`您最多可以使用${this.useNum}张`);
          this.conponList[idx].stepperVal--;
          this.useNum = item.stepperVal;
          this.set_radio(item);
        } else {
          this.useNum = item.stepperVal;
          this.set_radio(item);
        }
      } else {
        if (
          item.coupon_data.m_dec_money * item.stepperVal >
            this.$parent.inputPrice ||
          item.coupon_data.d_face_value * item.stepperVal >
            this.$parent.inputPrice
        ) {
          this.$message(`您最多可以使用${this.useNum}张`);
          this.conponList[idx].stepperVal--;
          this.useNum = item.stepperVal;
          this.set_radio(item);
        } else {
          this.useNum = item.stepperVal;
          this.set_radio(item);
        }
      }
    },
    useReduce(item) {
      this.useNum = item.stepperVal;
      this.set_radio(item);
    },
    select_Cou(item) {
      console.log(1212);
      for (let i = 0; i < this.conponList.length; i++) {
        const element = this.conponList[i];
        element.stepperVal = 1;
      }
      this.useNum = item.stepperVal;
      if (this.openMutex) {
        this.openIntegral = false;
      }
      this.set_radio(item);
    },
    // 选择优惠券
    set_radio(item) {
      // 点击显示单选按钮
      this.couponradio = item.id;
      console.log(item.coupon_type);
      switch (item.coupon_type) {
        // 满减券计算
        case 1:
          this.couponIds = item.coupon_data_ids.slice(0, this.useNum).join();
          this.upPrice = item.coupon_data.m_dec_money * this.useNum;
          this.bottom_ticket = `-${item.coupon_data.m_dec_money *
            this.useNum}元`;
          break;
        // 折扣券计算
        case 2:
          if (item.coupon_data.zhe_limit == 1) {
            // 是否开启了优惠券最大折扣金额
            this.bottom_ticket = `${item.coupon_data.zhe_discount}折`;
            console.log(
              this.$parent.inputPrice * item.coupon_data.zhe_discount
            );
            if (
              this.$parent.inputPrice *
                (1 - item.coupon_data.zhe_discount / 10) >
              Number(item.coupon_data.zhe_limit_money)
            ) {
              this.$message(
                `您使用的${item.coupon_data.zhe_discount}折优惠券,最大只能优惠${item.coupon_data.zhe_limit_money}元`
              );
              this.upPrice = Number(item.coupon_data.zhe_limit_money);
            } else {
              this.upPrice =
                Number(this.$parent.inputPrice) -
                (Number(this.$parent.inputPrice) *
                  Number(item.coupon_data.zhe_discount)) /
                  10;
            }
          } else {
            this.bottom_ticket = `${item.coupon_data.zhe_discount}折`;
            this.upPrice =
              Number(this.$parent.inputPrice) -
              (Number(this.$parent.inputPrice) *
                Number(item.coupon_data.zhe_discount)) /
                10;
          }
          this.couponIds = item.coupon_data_ids.slice(0, 1).join();
          break;
        // 代金券
        case 3:
          this.couponIds = item.coupon_data_ids.slice(0, this.useNum).join();
          this.bottom_ticket = `-${item.coupon_data.d_face_value *
            this.useNum}元`;
          this.upPrice = item.coupon_data.d_face_value * this.useNum;
          break;
        default:
          break;
      }
      this.conponType = item.coupon_type;
      this.calculatePrice();
    },
    // 清除状态
    noUseconpon(present) {
      this.conponList = [];
      this.useNum = 0;
      this.couponIds = "";
      this.bottom_ticket = "选择优惠券";
      this.upPrice = 0;
      this.couponradio = "";
      if (!present) {
        this.activeName = "1";
      }
    },
    // 获取积分抵扣
    get_point() {
      let data = {
        token: this.token,
        app_id: this.app_id,
        goods_id: this.oil_infor.goods.id,
        amount: this.inputPrice,
        payment_code: "cash",
        uid: this.user_infor[0].uid
      };
      get_point(data).then(res => {
        if (res.code == 200) {
          if (res.money == 0) {
            this.$message(res.msg);
            this.dedIntegral = 0;
            this.dedIntegralMoney = 0;
            // this.openIntegral = false;
          } else {
            this.dedIntegral = parseInt(res.maxUsePoint);
            this.dedIntegralMoney = res.money;
            if (this.openMutex) {
              // 开启互斥，取消优惠券选中
              this.couponradio = "";
              this.noUseconpon();
            }
            this.calculatePrice();
          }
        }
      });
    },
    // 是否开启互斥
    details() {
      let data = {
        token: this.token,
        app_id: this.app_id
      };
      getCouponSetting(data).then(res => {
        console.log("请求数据互斥数据", this.mutexData.length);
        this.mutexData =
          res.data.offline_buy != "" ? res.data.offline_buy.split(",") : [];
        // 默认选中数据
        if (this.mutexData.length >= 2) {
          this.openMutex = true; //开启互斥
        } else {
          this.openMutex = false; //关闭互斥
        }
      });
    },
    // 优惠项的选择
    pitchSet() {
      let choseShell = [];
      if (this.openMutex) {
        // 有互斥的情况
        if (this.mutexData.length == this.optionShell.length) {
          // 1.全部互斥的情况
          let num = this.priorityData();
          choseShell.push(num);
        } else {
          // 2.部分互斥时
          this.optionShell.forEach(item => {
            // 判断会员折扣是否享用
            if (!this.mutexData.includes(item)) {
              choseShell.push(item);
            }
          });
          let num = this.priorityData();
          choseShell.push(num); //默认取相互互斥的选项中的第一个数据
        }
      } else {
        // 沒有互斥
        choseShell = this.optionShell;
      }
      console.log("互斥數據", this.openMutex, choseShell);
      return choseShell;
    },
    priorityData() {
      let num = "";
      if (this.vipdiscounts_status != 0) {
        // 會員有优惠
        return (num = this.mutexData[0]);
      } else {
        // 没有优惠
        for (let i in this.mutexData) {
          if (this.mutexData[i] != "3") {
            num = this.mutexData[i];
            return num;
          }
        }
      }
    },
    // 判断互斥规则
    judgeRule(arr) {
      if (arr.indexOf("1") != -1 && arr.indexOf("2") != -1) {
        this.openMutex = true; //开启互斥
      } else {
        this.openMutex = false; //关闭互斥
      }
    },
    // 结账后刷新用户信息
    payEnd() {
      this.$emit("payEnd");
    }
  
  }
}
</script>